package org.mq.mymq.broker.slave;

import com.alibaba.fastjson2.JSON;
import org.mq.mymq.common.coder.TcpMsg;
import org.mq.mymq.common.dto.StartSyncReqDTO;
import org.mq.mymq.common.enums.BrokerEventCode;
import org.mq.mymq.common.event.EventBus;
import org.mq.mymq.common.remote.BrokerNettyRemoteClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * @ClassName SlaveSyncService
 * @Description 从节点同步服务：
 * 1. 从节点从NameServer中获取master节点地址
 * 2. 连接master节点，然后发送同步数据信号
 * 3. 接收master节点返回的同意同步信号数据
 * @Author jiarong_ye
 * @Date 2025/7/11 10:32
 * @Version 1.0
 */
public class SlaveSyncService {
    private static final Logger log = LoggerFactory.getLogger(SlaveSyncService.class);
    private BrokerNettyRemoteClient brokerNettyRemoteClient;

    public boolean connectMasterBrokerNode(String address) {
        String[] addressArr = address.split(":");
        try {
            brokerNettyRemoteClient = new BrokerNettyRemoteClient(addressArr[0], Integer.parseInt(addressArr[1]));
            brokerNettyRemoteClient.buildConnection(new SlaveSyncServerHandler(new EventBus("slave-sync-eventbus")));
            return true;
        } catch (Exception e) {
            log.error("error connect master broker", e);
        }
        return false;
    }

    public void sendStartSyncMsg() {
        StartSyncReqDTO startSyncReqDTO = new StartSyncReqDTO();
        startSyncReqDTO.setMsgId(UUID.randomUUID().toString());
        TcpMsg tcpMsg = new TcpMsg(BrokerEventCode.START_SYNC_MSG.getCode(), JSON.toJSONBytes(startSyncReqDTO));
        TcpMsg startSyncMsgResp = brokerNettyRemoteClient.sendSyncMsg(tcpMsg, startSyncReqDTO.getMsgId());
        log.info("startSyncMsgResp: {}", startSyncMsgResp);
    }
}
